#!/usr/bin/env python
# encoding: utf-8
"""
@author: youfeng
@email: youfeng243@163.com
@license: Apache Licence
@file: common.py
@time: 2017/8/24 22:56
"""
import requests
from tornado import gen
from tornado.httpclient import AsyncHTTPClient

from logger import AppLogger

log = AppLogger("dynamic-proxy-server.log").get_logger()


# 异步请求
@gen.coroutine
def fetch_coroutine(url):
    http_client = AsyncHTTPClient()
    response = yield http_client.fetch(url)

    if response is None or response.code != 200:
        raise gen.Return(None)
    else:
        raise gen.Return(response.body)


# get 同步请求
def request_get(url, timeout=None):
    timeout = 20 if timeout is None else timeout

    try:
        r = requests.get(url=url, timeout=timeout)
        if r is None:
            log.error("没有获得任何response: {}".format(url))
            return None
        if r.status_code != 200:
            log.error("返回状态码错误: {} {}".format(r.status_code, url))
            return None

        return r.text
    except Exception as e:
        log.error("访问链接失败: {}".format(url))
        log.exception(e)
    return None
